<?php
/**
 * Created by Dumitru Russu
 * User: developer
 * Date: 8/20/12
 * Time: 5:43 PM
 * To change this template use File | Settings | File Templates.
 */
class Page_Be_Cms_Projects extends Page {

    /**
     * @var Db_Projects
     */
    protected $tableObject;

    function __construct(){
        $this->idTableObject = get('id', 'int');
        $this->actionsTableObject = array(
            'addEditAction',
            'saveAction',
			'configPricesAction',
			'savePricesAction',
			'listPaymentMethodsAction',
			'addEditProjectPaymentMethodAction',
			'saveProjectPaymentMethodAction',
			'listProjectCountriesDeliveryMethodsAction',
			'addEditProjectCountriesDeliveryMethodsAction',
			'saveProjectCountryDeliveryMethodAction'
        );
        $this->classTableObject = 'Db_Projects';
        parent::__construct();
    }

    public function defaultAction(){
		if (perm('PROJECTS_EDIT')) {
        	$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit');
		}
		self::$TPL->appendJsFile('admin/projects');
        $allProjects = Db_Projects::getAllProjects();
        self::$TPL->assign('allProjects', $allProjects);
        self::$TPL->setBodyTemplate('list_projects');
        return array(
            'type' => 'display'
        );
    }

    public function addEditAction(){
		perm('PROJECTS_EDIT','/cms/projects');
		$allCountries = Db_Locale_Countries::findAllArray();
		$allLanguages = Db_Locale_Languages::getLangs($this->idTableObject);
		self::$TPL->assign('allCountries', $allCountries);
		self::$TPL->assign('allLanguages', $allLanguages);
		if ($this->idTableObject) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' &quot;' . t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) . '&quot;', '?action=addEdit&id=' . $this->idTableObject, true);

			$editProject = $this->tableObject->getProjectById($this->idTableObject);
			self::$TPL->assign('editProject', $editProject);

			$deliveryMethods = Db_Locale_DeliveryMethods::findAllArray();
			self::$TPL->assign('deliveryMethods', $deliveryMethods);

		} else {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit', true);
		}
		$currentLanguage = $this->tableObject->getProjectLanguages($this->idTableObject);
		self::$TPL->assign('currentLanguage', $currentLanguage);
		self::$TPL->setBodyTemplate('add_edit_project');
		return array(
			'type'=>'display'
		);
    }

    public function saveAction(){
		perm('PROJECTS_EDIT','/cms/projects');
        $projectName = strtolower(post('pr_name', 'string'));
        $projectIdentifier = strtolower(post('pr_identifer', 'string'));
		$projectTheme = strtolower(post('pr_theme', 'string'));
        $needsLogin = post('pr_needs_login', 'int');
        $projectDomainTest = post('pr_domain_test', 'string');
        $projectDomainLive = post('pr_domain_live', 'string');
        $projectResourcesTest = post('pr_resources_test', 'string');
        $projectResourcesLive = post('pr_resources_live', 'string');
        $projectEmail = post('pr_email', 'string');
        $projectCountryId = post('pr_country_id', 'int');
        $projectLanguages = post('project_languages', 'array');
        $this->message = t(T_FORM_MSG, 'success');

        if(!empty($projectName) && !empty($projectIdentifier) && !empty($projectDomainTest) && !empty($projectResourcesTest) &&
			!empty($projectDomainLive) && !empty($projectDomainLive) && !empty($projectCountryId) && !empty($projectLanguages) && !empty($projectTheme)) {

            $this->tableObject->pr_name = $projectName;
            $this->tableObject->pr_identifier = $projectIdentifier;
			$this->tableObject->pr_theme = $projectTheme;
            $this->tableObject->pr_needs_login = $needsLogin;
            $this->tableObject->pr_domain_test = $projectDomainTest;
            $this->tableObject->pr_domain_live = $projectDomainLive;
            $this->tableObject->pr_resources_test = $projectResourcesTest;
            $this->tableObject->pr_resources_live = $projectResourcesLive;
            $this->tableObject->pr_email = $projectEmail;
            $this->tableObject->pr_country_id = $projectCountryId;

            if(!$this->tableObject->save()){
                $this->error = true;
                $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
            } else {
              	$this->tableObject->saveProjectLanguages($this->tableObject->id, $projectLanguages);
            }

        } else {
            $this->error = true;
            $this->message = t(T_FORM_ERROR, 'required_fields');
        }
            return array(
                'type' => 'redirect',
                'query' => false
            );
    }

	public function configPricesAction() {
		perm('PROJECTS_EDIT','/cms/projects');
		self::$TPL->appendCssFile('admin/prices');
        self::$TPL->appendJsFile('admin/prices');

		if ($this->tableObject->id) {

			$this->addBreadcrumb(t(TAB_LABELS, 'config_prices'). "(" . t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) . ")", '', true);

			$projectId = $this->tableObject->id;
			self::$TPL->assign('projectId', $projectId);

            $allAmounts = Db_Products_Amounts::findAllArray();
			self::$TPL->assign('allAmounts', $allAmounts);

			$allSizes = Db_Products_Sizes::findAllArray();
			self::$TPL->assign('allSizes', $allSizes);

            $projectCategories = Db_Products_Categories::getCategoriesByProjectId($projectId);
			self::$TPL->assign('projectCategories', $projectCategories);

			$projectPrices = Db_Products_Prices::getPricesByProjectId($projectId);
			self::$TPL->assign('projectPrices', $projectPrices);

			self::$TPL->setBodyTemplate('edit_prices');

			return array(
				'type' => 'display'
			);
		} else {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			return array(
				'type' => 'redirect',
				'query' => false
			);
		}
	}

	public function  savePricesAction() {
		perm('PROJECTS_EDIT','/cms/projects');
		$this->message = t(T_FORM_MSG, 'success');

		$projectId = $this->tableObject->id;
		$priceArray = post('pc_price', 'array');
		$sizeArray = post('pc_size_id', 'array');
		$categoryArray = post('pc_category_id', 'array');
		$amountArray = post('am_amount', 'array');
		$i = 0;
		$data = array();
		foreach ($amountArray as $amount) {
			$data[] = array(
				'pc_price' => $priceArray[$i],
				'pc_size_id' => $sizeArray[$i],
				'pc_category_id' => $categoryArray[$i],
				'pc_amount_id' => $amount,
				'pc_project_id' => $projectId
			);
			$i++;
		}

		if (!self::$DB->insertBatch(TAB_PRICES, $data, true)) {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
		}
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}

	public function listPaymentMethodsAction() {
		self::$TPL->appendCssFile('admin/payment_methods');
		self::$TPL->appendJsFile('admin/payment_methods');
		$this->addBreadcrumb(t(T_PAGE_TITLE, 'payment_methods') . ' "' . t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) . '"', '?action=listPaymentMethods&id=' . $this->tableObject->objectArray->id, true);
		$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditProjectPaymentMethod&id=' . $this->tableObject->objectArray->id);
		if(!empty($this->tableObject->objectArray->id)) {
			$projectPaymentMethods = Db_Payments_ProjectsPaymentMethods::getProjectPaymentMethodsByProjectId($this->tableObject->id);
			self::$TPL->assign('projectPaymentMethods', $projectPaymentMethods);
		}

		self::$TPL->setBodyTemplate('list_projects_payment_methods');
		return array(
			'type' => 'display'
		);
	}

	public function addEditProjectPaymentMethodAction() {
		perm('PAYMENT_METHODS_ERROR_CODES_EDIT');
		self::$TPL->appendCssFile('admin/payment_methods');
		self::$TPL->appendJsFile('admin/payment_methods');
		$this->addBreadcrumb(t(T_PAGE_TITLE, 'payment_methods') .' "'. t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) .'"', '?action=listPaymentMethods&id=' . $this->tableObject->objectArray->id);

		$projectPaymentMethod = new Db_Payments_ProjectsPaymentMethods(get('childId', 'int'));

		if(!empty($projectPaymentMethod->objectArray->id)) {
			$paymentMethod = Db_Payments_PaymentMethods::findById($projectPaymentMethod->objectArray->ppm_payment_method_id);
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' "' . t($paymentMethod->pm_module, $paymentMethod->pm_name) .'"', '?action=addEditProjectPaymentMethod&id=' . $this->tableObject->objectArray->id . '&childId=' . $projectPaymentMethod->objectArray->id, true);
			self::$TPL->assign('projectPaymentMethod', $projectPaymentMethod->objectArray);
		} else {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditProjectPaymentMethod&id=' . $this->tableObject->objectArray->id, true);
		}

		$paymentMethods = Db_Payments_PaymentMethods::findAll();
		self::$TPL->assign('paymentMethods', $paymentMethods);

		self::$TPL->setBodyTemplate('add_edit_project_payment_method');
		return array(
			'type' => 'display'
		);
	}

	public function saveProjectPaymentMethodAction() {
		perm('PAYMENT_METHODS_ERROR_CODES_EDIT');
		$this->message = t(T_FORM_MSG, 'success');
		$projectPaymentMethodId = (get('childId', 'int') ? get('childId', 'int') : null);
		$projectPaymentMethods = new Db_Payments_ProjectsPaymentMethods($projectPaymentMethodId);
		$projectPaymentMethods->ppm_invoice_note = post('ppm_invoice_note', 'int');
		$projectPaymentMethods->ppm_invoice_text = post('ppm_invoice_text', 'str');
		$projectPaymentMethods->ppm_email_note = post('ppm_email_note', 'int');
		$projectPaymentMethods->ppm_email_text = post('ppm_email_text', 'str');
		$projectPaymentMethods->ppm_payment_method_id = post('ppm_payment_method_id', 'int');
		$projectPaymentMethods->ppm_project_id = $this->tableObject->objectArray->id;
		$projectPaymentMethods->ppm_show_on_page = post('ppm_show_on_page', 'int');
		if(!empty($projectPaymentMethods->ppm_payment_method_id)) {
			if(!$projectPaymentMethods->save()) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			}
		}
		if(empty($projectPaymentMethodId)) {
			$paymentMethod = new Db_Payments_ProjectsPaymentMethods($projectPaymentMethods->id);
			$paymentMethod->positionCommonFields = array(
				'ppm_project_id' => $this->tableObject->objectArray->id
			);

			if(!$paymentMethod->positionSetLast()) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			}
		}

		return array(
			'type' => 'redirect',
			'content' => '?action=listPaymentMethods&id=' . $this->tableObject->objectArray->id
		);
	}

	public function deleteProjectPaymentMethodAction() {
		perm('PAYMENT_METHODS_ERROR_CODES_EDIT');
		$this->message = t(T_FORM_MSG, 'success');
		if(!Db_Payments_ProjectsPaymentMethods::abstractDelete(get('childId', 'int'))) {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
		}
		$paymentMethod = new Db_Payments_ProjectsPaymentMethods(get('childId', 'int'));
		$paymentMethod->positionCommonFields = array(
			'ppm_project_id' => get('id', 'int')
		);
		$paymentMethod->positionCleanUp();

		return array(
			'type' => 'redirect',
			'content' => '?action=listPaymentMethods&id=' . get('id', 'int')
		);
	}

	public function saveProjectPaymentMethodsPositionAction() {
		perm('PAYMENT_METHODS_ERROR_CODES_EDIT');
		$btnAction = post('btnAction', 'string');
		$paymentMethodId = post('currentId', 'int');

		$paymentMethod = new Db_Payments_ProjectsPaymentMethods($paymentMethodId);

		$paymentMethod->positionCommonFields = array(
			'ppm_project_id' => $paymentMethod->objectArray->ppm_project_id
		);
		$this->moveUpDownAjax($btnAction, $paymentMethod);
	}

	public function listProjectCountriesDeliveryMethodsAction() {
		self::$TPL->appendCssFile('admin/payment_methods');
		self::$TPL->appendJsFile('admin/payment_methods');
		$this->addBreadcrumb(t(T_PAGE_TITLE, 'delivery_methods') . ' "' . t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) . '"', '?action=listProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id, true);
		$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id);

		$projectCountriesDeliveryMethods = Db_Locale_ProjectCountriesDeliveryMethods::getCountryDeliveryMethodsByProjectId($this->tableObject->objectArray->id);
		self::$TPL->assign('projectCountriesDeliveryMethods', $projectCountriesDeliveryMethods);

		self::$TPL->setBodyTemplate('list_project_countries_delivery_methods');
		return array(
			'type' => 'display'
		);
	}

	public function addEditProjectCountriesDeliveryMethodsAction() {
		perm('PROJECT_COUNTRIES_DELIVERY_METHODS_EDIT');
		self::$TPL->appendJsFile('admin/delivery_methods');

		$projectCountriesDeliveryMethods = new Db_Locale_ProjectCountriesDeliveryMethods(get('child', 'int'));
		$this->addBreadcrumb(t(T_PAGE_TITLE, 'delivery_methods') . ' "' . t(T_PROJECT_TITLE, $this->tableObject->objectArray->pr_name) . '"', '?action=listProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id);
		if(!empty($projectCountriesDeliveryMethods->objectArray->id)) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' "' . $projectCountriesDeliveryMethods->objectArray->pcdm_description .'"', '?action=addEditProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id, true);
			self::$TPL->assign('projectCountriesDeliveryMethods', $projectCountriesDeliveryMethods->objectArray);
			$deliveryDays = Db_Locale_ProjectCountriesDeliveryMethodsDays::getProjectCountriesDeliveryDays(get('child', 'int'));
			self::$TPL->assign('deliveryDays', $deliveryDays);

		} else {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id, true);
		}

		$deliveryMethods = Db_Locale_DeliveryMethods::findAll();
		self::$TPL->assign('deliveryMethods', $deliveryMethods);

		$countries = Db_Locale_Countries::findAll();
		self::$TPL->assign('countries', $countries);

		$days = Db_Locale_ProjectCountriesDeliveryMethodsDays::getEnumValues('pcdy_day');
		self::$TPL->assign('days', $days);

		self::$TPL->setBodyTemplate('add_edit_project_country_delivery_method');
		return array(
			'type' => 'display'
		);
	}

	public function saveProjectCountryDeliveryMethodAction() {
		perm('PROJECT_COUNTRIES_DELIVERY_METHODS_EDIT');
		$this->message = t(T_FORM_MSG, 'success');
		$projectCountriesDeliveryMethodId = (get('childId', 'int') ? get('childId', 'int') : null);
		$projectCountriesDeliveryMethods = new Db_Locale_ProjectCountriesDeliveryMethods($projectCountriesDeliveryMethodId);
		$projectCountriesDeliveryMethods->pcdm_available_for_sample = post('pcdm_available_for_sample', 'int');
		$projectCountriesDeliveryMethods->pcdm_country_id = post('pcdm_country_id', 'int');
		$projectCountriesDeliveryMethods->pcdm_delivery_method_id = post('pcdm_delivery_method_id', 'int');
		$projectCountriesDeliveryMethods->pcdm_description = strtolower(post('pcdm_description', 'str'));
		$projectCountriesDeliveryMethods->pcdm_price = post('pcdm_price', 'str');
		$projectCountriesDeliveryMethods->pcdm_show_on_page = post('pcdm_show_on_page', 'int');
		$projectCountriesDeliveryMethods->pcdm_is_default = post('pcdm_is_default', 'int');
		$projectCountriesDeliveryMethods->pcdm_days_restrictions = post('pcdm_days_restrictions', 'int');
		$projectCountriesDeliveryMethods->pcdm_project_id = $this->tableObject->objectArray->id;

		$existProjectDeliveryDefault = Db_Locale_ProjectCountriesDeliveryMethods::findByFields(array(
			'pcdm_project_id' => $projectCountriesDeliveryMethods->pcdm_project_id,
			'pcdm_is_default' => 1
		));

		$projectCountriesDeliveryFind = Db_Locale_ProjectCountriesDeliveryMethods::findByFields(array(
			'pcdm_project_id' => $projectCountriesDeliveryMethods->pcdm_project_id,
			'pcdm_country_id' => $projectCountriesDeliveryMethods->pcdm_country_id,
			'pcdm_delivery_method_id' => $projectCountriesDeliveryMethods->pcdm_delivery_method_id
		));
		if((empty($existProjectDeliveryDefault)) || ($existProjectDeliveryDefault->id == $projectCountriesDeliveryMethods->id) || $projectCountriesDeliveryMethods->pcdm_is_default != $existProjectDeliveryDefault->pcdm_is_default) {

		if((empty($projectCountriesDeliveryFind) || ($projectCountriesDeliveryFind->id == $projectCountriesDeliveryMethods->id))) {

			if(!empty($projectCountriesDeliveryMethods->pcdm_description) && !empty($projectCountriesDeliveryMethods->pcdm_country_id) &&
				!empty($projectCountriesDeliveryMethods->pcdm_delivery_method_id) && !empty($projectCountriesDeliveryMethods->pcdm_price)) {

				if(!$projectCountriesDeliveryMethods->save(true)) {
					$this->error = true;
					$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
				}
				if(empty($projectCountriesDeliveryMethodId)) {
					$countryDeliveryMethod = new Db_Locale_ProjectCountriesDeliveryMethods($projectCountriesDeliveryMethods->id);
					$countryDeliveryMethod->positionCommonFields = array(
						'pcdm_project_id' => $this->tableObject->objectArray->id
					);
					if(!$countryDeliveryMethod->positionSetLast()) {
						$this->error = true;
						$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
					}
				}
				if(!empty($projectCountriesDeliveryMethodId)) {
					Db_Locale_ProjectCountriesDeliveryMethodsDays::deleteByField('pcdy_project_delivery_id', $projectCountriesDeliveryMethodId, 0);
					if($projectCountriesDeliveryMethods->pcdm_days_restrictions == 1) {
						$deliveryDays = post('deliveryDays', 'array');

						foreach($deliveryDays as $day => $deliveryDay) {
							$deliveryDay['pcdy_day'] = $day;
							$deliveryDay['pcdy_project_delivery_id'] = $projectCountriesDeliveryMethodId;
							$deliveryDays['result'][] = $deliveryDay;
						}
						Db_Locale_ProjectCountriesDeliveryMethodsDays::insertBatch($deliveryDays['result']);
					}
				}
			} else {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			}
		} else {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'duplicate_entry');
		}
		} else {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'exist_is_default');
		}
		$child = (!empty($projectCountriesDeliveryMethodId) ?  '&child=' . $projectCountriesDeliveryMethodId : null );
		return array(
			'type' => 'redirect',
			'content' => '?action=addEditProjectCountriesDeliveryMethods&id=' . $this->tableObject->objectArray->id . $child
		);
	}


	public function deleteProjectCountryDeliveryMethodAction() {
		perm('PROJECT_COUNTRIES_DELIVERY_METHODS_EDIT');
		$this->message = t(T_FORM_MSG, 'success');
		if(!Db_Locale_ProjectCountriesDeliveryMethods::abstractDelete(get('child', 'int'))) {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
		}
		$projectDeliveryMethod = new Db_Locale_ProjectCountriesDeliveryMethods(get('childId', 'int'));
		$projectDeliveryMethod->positionCommonFields = array(
			'pcdm_project_id' => get('id', 'int')
		);
		$projectDeliveryMethod->positionCleanUp();
		return array(
			'type' => 'redirect',
			'content' => '?action=listProjectCountriesDeliveryMethods&id=' . get('id', 'int')
		);
	}

	public function saveProjectCountryDeliveryMethodsPositionAction() {
		perm('PROJECT_COUNTRIES_DELIVERY_METHODS_EDIT');
		$btnAction = post('btnAction', 'string');
		$projectCountriesDeliveryMethodId = post('currentId', 'int');

		$projectCountriesDeliveryMethod = new Db_Locale_ProjectCountriesDeliveryMethods($projectCountriesDeliveryMethodId);

		$projectCountriesDeliveryMethod->positionCommonFields = array(
			'pcdm_project_id' => $projectCountriesDeliveryMethod->objectArray->pcdm_project_id
		);
		$this->moveUpDownAjax($btnAction, $projectCountriesDeliveryMethod);
	}


}